import axios from 'axios';

export interface Topic {
  id: number;
  title: string;
  posts_count: number;
  created_at: string;
  like_count?: number;
  post_stream: {
    posts: Post[];
    stream: number[];
  };
}

export interface Post {
  id: number;
  name: string;
  username: string;
  created_at: string;
  updated_at: string;
  cooked: string; // HTML content
  raw: string;   // Raw text content
}

export interface SearchResult {
  topics: Topic[];
  posts: Post[];
}

export class WaterSourceAPI {
  private baseUrl: string;
  private cookie: string;

  constructor(cookie: string = '') {
    this.baseUrl = 'https://shuiyuan.sjtu.edu.cn';
    this.cookie = cookie;
  }

  /**
   * 设置或更新Cookie
   */
  public setCookie(cookie: string): void {
    this.cookie = cookie;
  }

  /**
   * 获取请求头
   */
  private getHeaders(): Record<string, string> {
    return {
      'Cookie': this.cookie,
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
      'Accept': 'application/json, text/javascript, */*; q=0.01',
      'X-Requested-With': 'XMLHttpRequest'
    };
  }

  /**
   * 搜索主题和帖子
   */
  public async search(query: string, page: number = 1): Promise<SearchResult> {
    try {
      console.log(`正在搜索关键词: ${query}, 页码: ${page}`);
      const response = await axios.get(`${this.baseUrl}/search.json`, {
        params: {
          q: query,
          page: page
        },
        headers: this.getHeaders()
      });

      return response.data;
    } catch (error) {
      console.error('搜索失败:', error instanceof Error ? error.message : String(error));
      throw new Error('搜索失败');
    }
  }

  /**
   * 获取主题详情，包含所有帖子
   */
  public async getTopic(topicId: string): Promise<Topic> {
    try {
      console.log(`正在获取主题: ${topicId}`);
      const response = await axios.get(`${this.baseUrl}/t/${topicId}.json`, {
        headers: this.getHeaders()
      });

      return response.data;
    } catch (error) {
      console.error('获取主题失败:', error instanceof Error ? error.message : String(error));
      throw new Error(`获取主题失败: ${topicId}`);
    }
  }

  /**
   * 获取特定帖子内容
   */
  public async getPost(postId: string): Promise<Post> {
    try {
      console.log(`正在获取帖子: ${postId}`);
      const response = await axios.get(`${this.baseUrl}/posts/${postId}.json`, {
        headers: this.getHeaders()
      });

      return response.data;
    } catch (error) {
      console.error('获取帖子失败:', error instanceof Error ? error.message : String(error));
      throw new Error(`获取帖子失败: ${postId}`);
    }
  }

  /**
   * 获取主题中多个帖子
   */
  public async getTopicPosts(topicId: string, postIds: string[]): Promise<Post[]> {
    try {
      if (!postIds || postIds.length === 0) {
        return [];
      }

      console.log(`正在获取主题 ${topicId} 的多个帖子: ${postIds.join(', ')}`);
      const params: Record<string, string> = {};
      
      // 构建post_ids[]参数
      postIds.forEach((id, index) => {
        params[`post_ids[${index}]`] = id;
      });

      const response = await axios.get(`${this.baseUrl}/t/${topicId}/posts.json`, {
        params,
        headers: this.getHeaders()
      });

      return response.data.post_stream.posts;
    } catch (error) {
      console.error('获取多个帖子失败:', error instanceof Error ? error.message : String(error));
      throw new Error(`获取多个帖子失败: ${topicId}`);
    }
  }

  /**
   * 提取帖子纯文本内容
   */
  public extractPostContent(post: Post): string {
    // 优先使用raw字段(原始文本)
    if (post.raw) {
      return post.raw;
    }
    
    // 如果没有raw字段，则从cooked(HTML)中提取文本
    if (post.cooked) {
      // 使用简单的正则表达式去除HTML标签
      return post.cooked
        .replace(/<[^>]*>/g, '') // 移除所有HTML标签
        .replace(/&nbsp;/g, ' ') // 替换HTML空格实体
        .replace(/&lt;/g, '<')   // 替换小于号
        .replace(/&gt;/g, '>')   // 替换大于号
        .replace(/&amp;/g, '&')  // 替换&符号
        .replace(/&quot;/g, '"') // 替换引号
        .replace(/\s+/g, ' ')    // 合并多个空格
        .trim();                 // 移除两端空白
    }
    
    return '';
  }
} 